from PIL import Image
import base64
from io import BytesIO
import os
import shutil

from flask import Flask, request
import json
from gevent.pywsgi import WSGIServer
import time

import global_config
import model_precit
import tag_img_online

if __name__ == '__main__':
    app = tag_img_online.app

def base64_to_image(base64_str, image_path=None):
    """
    base64转图片
    :param base64_str: base64编码
    :param image_path: 图片路径
    :return:
    """
#     base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
    byte_data = base64.b64decode(base64_str)
    image_data = BytesIO(byte_data)
    img = Image.open(image_data)
    if image_path:
        img.save(image_path)
    return img

def discern(jsonData):
    """
    识别验证码
    :param jsonData: 请求参数 json格式
    :return:
    """
    # 验证码的base64格式
    v_code = jsonData.get('v_code')
    im = base64_to_image(v_code)
    try:
        value = model_precit.predict_img(im)
    except BaseException as b:
        print("发生异常：{},预测信息为：{}".format(str(b), jsonData))
        return getResultJson(False, "", str(b))
    img_name = ''
    try:
        if global_config.my_config.is_save_api_img:
            img_name = "{}-{}.{}".format(value, str(time.time()).replace(".", ""), 'png')
            path = os.path.join(global_config.api_img_save_path_uncheck, img_name)
            im.save(path)
    except BaseException as b:
        print("保存文件失败，发生异常：{},预测信息为：{}".format(b, jsonData))
        return getResultJson(True, value, "预测成功，保存文件失败")
    return getResultJson(True, value, "识别成功", img_name)

def getResultJson(status, v_code, msg, img_name=None):
    """
    获取结果的json字符串
    :param img_name: 图片的名称
    :param status: 结果状态
    :param v_code: 验证码
    :param msg: 信息
    :return:
    """
    result_json = {}
    result_json["status"] = status
    result_json["v_code"] = v_code
    result_json["msg"] = msg
    result_json["img_name"] = img_name
    return json.dumps(result_json, ensure_ascii=False)

@app.route('/discern', methods=['POST'])
def app_discern():
    try:
        # 接受前端发来的数据
        s = time.time()
        data = json.loads(request.get_data())
        result_data = discern(data)
        e = time.time()
        # print('识别的信息为：{}，耗时：{} ms，请求参数：{}'.format(result_data, int((e - s) * 1000), data))
        print('识别的信息为：{}，耗时：{} ms'.format(result_data, int((e - s) * 1000)))
        return result_data
    except BaseException as b:
        print("发生异常：{}".format(b))
        return getResultJson(False, "", "识别失败，参数错误")

@app.route('/confirm/<img_name>/<confirm_status>', methods=['GET'])
def app_confirm(img_name, confirm_status):
    try:
        # 接受前端发来的数据
        s = time.time()
        # print(img_name, confirm_status)
        path = os.path.join(global_config.api_img_save_path_uncheck, img_name)
        if os.path.exists(path):
            if '1' == confirm_status:
                shutil.move(path, global_config.api_img_save_path_check_right + '/' + img_name)
            else:
                shutil.move(path, global_config.api_img_save_path_check_wrong + '/' + img_name)
        else:
            return getResultJson(False, "", '确认失败，文件不存在')
        e = time.time()
        print('确认的信息为：img_name：{}，status：{} ，耗时：{} ms'.format(img_name, confirm_status, int((e - s) * 1000)))
        return getResultJson(True, "", '确认成功')
    except BaseException as b:
        print("发生异常：{}".format(b))
        return getResultJson(False, "", "确认失败，参数错误")

def init_all():
    # 初始化模型
    model_precit.init_model()
    # 初始化api目录
    if not os.path.exists(global_config.api_img_save_path_uncheck):
        os.makedirs(global_config.api_img_save_path_uncheck)
    if not os.path.exists(global_config.api_img_save_path_check_right):
        os.makedirs(global_config.api_img_save_path_check_right)
    if not os.path.exists(global_config.api_img_save_path_check_wrong):
        os.makedirs(global_config.api_img_save_path_check_wrong)
    if not os.path.exists(global_config.api_img_save_path_check_manual):
        os.makedirs(global_config.api_img_save_path_check_manual)

if __name__ == '__main__':

    init_all()
    # app.run(host='0.0.0.0', port=80, debug=False)
    http_server = WSGIServer(('0.0.0.0', 80), app)
    print('服务器启动完成')
    http_server.serve_forever()

